// handle url change requests from context-menu.js
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if(request.url) {
        window.location.href = request.url;
    }
});

chrome.extension.sendRequest({command: "options"}, function(response) {
    var smileys = response.smileys;
    if(response.smileysEnabled && smileys) {
        convertSmileys(smileys);
    }
    if(response.hideIgnoredEnabled) {
        hideIgnored();
    }
    if(response.eggsEnabled) {
        eggs();
    }
	if(response.delaySecs > 0) {
		setTimeout(function(){rename(response)}, response.delaySecs*1000);
	} else {
		rename(response);
	}
});

function eggs() {
    // one egg max
    if(floppyEgg()) {
        eggIcon();
        return;
    }
    if(edEgg()) {
        eggIcon();
        return;
    }
    if(gaEgg()) {
        eggIcon();
        return;
    }              
}

function eggIcon() {
    chrome.extension.sendRequest({command: "egg"});    
}

function gaEgg() {
    // 31
    return avatarEgg('ga', 'http://i.imgur.com/oaUjE.gif', 45, 35, 3000);
}

function floppyEgg() {
    //91
    return avatarEgg('floppy', 'http://forums.kipin.net/images/smilies/icon_floppy.gif', 50, 50, 3000);
}

function edEgg() {
    // 61
    return avatarEgg('ed', 'http://forums.kipin.net/download/file.php?avatar=793_1294966427.jpg', 80, 79, 3000);
}

function avatarEgg(name, image, height, width, randMultiplier) {
    if(!onViewTopicPage()) {
       return false;
    }    
    
    var returnValue = false;
    var rand = Math.floor(Math.random()*randMultiplier);
    if(rand == 1) {
        console.log(name + ' egg running');
        swapAllAvatars(image, height, width);
        returnValue = true;    
    }
    return returnValue;    
}

function onViewTopicPage() {
    var returnValue = false;
    if(window.location.href.indexOf('viewtopic.php') != -1) {
        returnValue = true;;
    }
    return returnValue;   
}

function swapAllAvatars(image, height, width) {
    console.log('height: ' + height + ' width: ' + width);
    var imageElements = document.getElementsByTagName('img');
    for(var i = 0; i < imageElements.length; i++) {
        if(imageElements[i].alt == 'User avatar') {
            imageElements[i].src = image;
            imageElements[i].height = height;
            imageElements[i].width = width;   
        }
    }
}

function hideIgnored() {
    var ignoredElements = document.getElementsByClassName('ignore');
    for(var i = 0; i < ignoredElements.length; i++) {
        ignoredElements[i].parentNode.parentNode.style.display = 'none';
        // remove <hr> divider, have to go down 2 siblings as first is #text
        ignoredElements[i].parentNode.parentNode.nextSibling.nextSibling.style.display = 'none';
    }
}

function convertSmileys(smileys) {
    var id = document.getElementById('message');
    if(id !== 'undefined') {
        var submitElements = document.getElementsByClassName('button1');
        for(var i = 0; i < submitElements.length; i++) {
            if(submitElements.item(i).name == 'preview' || submitElements.item(i).name == 'post') {
               submitElements.item(i).addEventListener('click', function () {
                   replaceSmileys(smileys);
               }, false);
            }   
        }
    }
}

function rename(response) {
    if(response.userReplaceEnabled) {
        swapKey(response.userList, 'username-coloured');    
    }
	if(response.wordReplaceEnabled) {
	    replaceText(response.wordList, 'content');   
	}	
}

function swapKey(list, className) {
	if(!list) {
		return;
	}
	
	keyArray = loadKeyArray(list);
	var elementList, element, orgKey;
	elementList = document.getElementsByClassName(className);
	for(var i = 0; i < elementList.length; i++) {
		element = elementList[i];
		orgKey = element.innerHTML;
		if(orgKey in keyArray) {
			element.innerHTML = keyArray[orgKey];
		}
	}	
}

function replaceText(list, className) {
	if(!list) {
		return;
	}
	
	listArray = loadTextArray(list);
	var elementList, element, orgText, newText;
	elementList = document.getElementsByClassName(className);
	for(var i = 0; i < elementList.length; i++) {
		element = elementList[i];
		orgText = element.innerHTML;
		for(var j = 0; j < listArray.length; j++) {
		    if(orgText.indexOf(listArray[j][0]) != -1) {
                newtText = orgText.replace(listArray[j][0], listArray[j][1]);
                element.innerHTML = newtText;		        
		    }
		}
	}	
}

function replaceSmileys(smileys) {
    var id = document.getElementById('message');
    linesArray = loadTextArray(smileys);
    var regex;
    for(var i = 0; i < linesArray.length; i++) {
        // use g to replace all
        regex = new RegExp(linesArray[i][0], 'g');
        id.value = id.value.replace(regex, '[img]' + linesArray[i][1] + '[/img]');    
    }
}

function loadKeyArray(list) {
	var returnValue = new Array();
	list = convertLineBreaks(list);
	var linesArray = list.split('\n');
	var chunkArray = new Array();
	for(var i = 0; i < linesArray.length; i++) {
		chunkArray = linesArray[i].split('|');
		returnValue[chunkArray[0]] = chunkArray[1];
	}	
	return returnValue;
}

function loadTextArray(list) {
	var returnValue = new Array();
	list = convertLineBreaks(list);
	var linesArray = list.split('\n');
	var chunkArray = new Array();
	for(var i = 0; i < linesArray.length; i++) {
		chunkArray = linesArray[i].split('|');
		returnValue[i] = new Array(2);
		returnValue[i][0] = chunkArray[0];
		returnValue[i][1] = chunkArray[1];
	}
	return returnValue;
}

// should test on chrome to see if this is even needed
function convertLineBreaks(string) {
	// windows
	string.replace(String.fromCharCode(13)+String.fromCharCode(10), String.fromCharCode(10));
	// mac
	string.replace(String.fromCharCode(13), String.fromCharCode(10));
	return string;
}